package com.xxx.reportingsystem.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xxx.common.Result;
import com.xxx.pojo.UserOperate;
import com.xxx.service.UserOperateService;
import com.xxx.utils.ExportUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;

@Slf4j
@RequestMapping("/userOperate")
@RestController
public class UserOperateController {
    @Autowired
    private UserOperateService userOperateService;

    @Transactional
    @PostMapping("/select")
    @PreAuthorize("hasAnyAuthority('sys:select:userLogin')")
    public Result selectUserLoginCondition(UserOperate userOperate, @RequestParam("current") Integer current, @RequestParam("size") Integer size, @RequestParam(required = false,value = "starTime") String starTime, @RequestParam(required = false,value = "endTime") String endTime){
        LambdaQueryWrapper<UserOperate> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(userOperate.getUserName() != null && userOperate.getUserName().length()>0,UserOperate::getUserName,userOperate.getUserName())
                .like(userOperate.getAffiliation() != null && userOperate.getAffiliation().length()>0,UserOperate::getAffiliation,userOperate.getAffiliation())
                .between(starTime != null && endTime != null ,UserOperate::getUpdateTime,starTime,endTime)
                .eq(UserOperate::getStatus,0).eq(UserOperate::getDelete,0);
        IPage iPage = new Page<>(current,size);
        IPage page = userOperateService.page(iPage);
        HashMap<String, Object> map = new HashMap<>();
        map.put("list",page.getRecords());
        map.put("total", page.getTotal());
        return Result.success("",map);
    }

    @Transactional
    @GetMapping("/export")
    @PreAuthorize("hasAnyAuthority('sys:select:userOperate')")
    public void exportUserExcel(HttpServletResponse response) {
        try {
            ExportUtil.setExcelResponseProp(response, "用户修改表");
            List<UserOperate> userOperates = userOperateService.list();
            EasyExcel.write(response.getOutputStream())
                    .head(UserOperate.class)
                    .excelType(ExcelTypeEnum.XLSX)
                    .sheet("用户修改表")
                    .doWrite(userOperates);
            userOperateService.addLogManage("用户管理","导出修改用户","导出");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
